<template>
  <el-card shadow="never">
    <el-tabs v-model="tabName">
      <el-tab-pane label="全院科室申报" name="first">
        <el-form ref="form" :model="form" :rules="rules" label-suffix="：" label-width="120px">
          <el-row :span="16">
            <el-col>
              <el-form-item label="标题" prop="applyTitle">
                <el-input v-model="form.applyTitle" placeholder="请输入标题" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="申请人">
                <el-input v-model="form.applyUser" :readOnly="true" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属科室">
                <el-input v-model="form.deptName" :readOnly="true" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="时间">
                <el-date-picker
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  v-model="form.applyTime1"
                  placeholder="请选择"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-tooltip class="item" effect="dark" content="添加项目" placement="top">
                <el-button
                  size="small"
                  class="mb20"
                  icon="el-icon-plus"
                  type="primary"
                  @click="handleAddItems"
                />
              </el-tooltip>
            </el-col>
          </el-row>
        </el-form>
        <el-row class="mb20" :gutter="16" v-for="(item,index) in itemArr" :key="index">
          <el-col>
            <h3>
              项目名称：{{ item.evalItemName }}
              <el-button type="danger" class="fr" @click="handleDeleteItem(item)" size="small">删除</el-button>
            </h3>
            <div class="flex">
              <p class="mr10">项目内容：{{ item.evalItemContent }}</p>
              <p class="mr10">项目标准值：{{ item.rewardStandard }}</p>
              <p class="mr10">项目类型：{{ item.rewardOrientation === 1 ? '分' : '钱' }}</p>
              <p>上下限：{{ item.rewardUpLimit ? item.rewardUpLimit : '无上限' }}至{{ item.rewardLowLimit ? item.rewardLowLimit : '无下限' }}</p>
            </div>
            <el-button class="mb20" @click="handleTableAdd(item)">追加科室</el-button>
          </el-col>
          <el-col>
            <e-table
              ref="eTable"
              :tableData="item.tableData"
              :columns="columns"
              :loading="loading"
              :pageObj="null"
            >
              <el-table-column label="责任对象类型" align="center" slot="type">
                <template>科室</template>
              </el-table-column>
              <el-table-column label="事件时间" slot="date" align="center">
                <template slot-scope="scope">
                  <template>
                    <el-date-picker
                      style="width: 100%"
                      type="date"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      v-model="scope.row.eventDate"
                      placeholder="请选择"
                    />
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="责任对象" align="center" slot="target">
                <template slot-scope="scope">
                  <dept-select
                    :selectValue="scope.row.targetDeptId"
                    @select="e => handleDeptSelect(e, scope.row, item)"
                  />
                </template>
              </el-table-column>
              <el-table-column label="奖惩" align="center" slot="reward">
                <template slot-scope="scope">
                  <!-- <template v-if="scope.row.rewardType !== 3">
                    {{
                    scope.row.rewardType === 1? '奖' : '惩'
                    }}
                  </template>
                  <template v-else>-->
                  <el-radio-group v-model="scope.row.rewardType" size="small">
                    <el-radio-button :label="1">奖</el-radio-button>
                    <el-radio-button :label="2">惩</el-radio-button>
                  </el-radio-group>
                  <!-- </template> -->
                </template>
              </el-table-column>
              <el-table-column label="值" align="center" slot="value">
                <template slot-scope="scope">
                  <el-input
                    @input="e => handleRewardValue(e, scope.row, item)"
                    v-model.number="scope.row.rewardValue"
                  />
                </template>
              </el-table-column>
              <el-table-column label="说明" align="center" slot="notice">
                <template slot-scope="scope">
                  <el-input
                    maxlength="249"
                    show-word-limit
                    v-model="scope.row.eventDescribe"
                    type="textarea"
                    :rows="2"
                  />
                </template>
              </el-table-column>
              <el-table-column label="图片" align="center" slot="image">
                <template slot-scope="scope">
                  <!-- <template v-if="scope.row.photoList"></template> -->
                  <template>
                    <el-upload
                      accept=".jpg, .png, .jpeg, .gif"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :multiple="true"
                      :on-preview="file => handlePreview(file, scope.row, item)"
                      :file-list="scope.row.fileList"
                      :on-remove="(file,fileList) => handleRemove(file, fileList, scope.row, item)"
                      :http-request="info => customRequest( info, scope.row, item )"
                    >
                      <el-button>
                        <i class="el-icon-upload" />上传
                      </el-button>
                    </el-upload>
                  </template>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="50" align="center" slot="action">
                <template slot-scope="scope">
                  <a class="red" @click="handleDelete(scope.row, item)">删除</a>
                </template>
              </el-table-column>
            </e-table>
          </el-col>
        </el-row>
        <div class="tl-center">
          <el-button @click="handleSubmit" class="mt20" type="primary">提交</el-button>
        </div>
      </el-tab-pane>
      <el-tab-pane label="申报记录" name="second">
        <declare-table ref="declareTable" />
      </el-tab-pane>
    </el-tabs>
    <preview-modal ref="previewModal" />
    <declare-modal @addItem="handlePostArr" ref="declareModal" />
  </el-card>
</template>

<script>
import DeptSelect from '@/components/DeptSelect'
import DeclareModal from '../declare/DeclareModal'
import DeclareTable from './DeclareTable'
import PreviewModal from '@/components/PreviewModal'
import { applyCreate } from '@/api/eval'
import { openNotification } from '@/utils/util'
import { saveOnlyUploads } from '@/api/supplier'

export default {
  components: {
    PreviewModal,
    DeclareTable,
    DeptSelect,
    DeclareModal
  },
  data() {
    return {
      tabName: 'first',
      form: {},
      itemArr: [],
      tableData: [],
      userInfo: this.$store.getters.userInfo,
      columns: [
        {
          slot: 'type'
        },
        {
          slot: 'date'
        },
        {
          slot: 'target'
        },
        {
          slot: 'reward'
        },
        {
          slot: 'value'
        },
        {
          slot: 'notice'
        },
        {
          slot: 'image'
        },
        {
          slot: 'action'
        }
      ],
      rules: {
        applyTitle: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      userArr: [],
      fileList: [],
      loading: false
    }
  },
  methods: {
    // 奖惩值输入处理
    handleRewardValue(e, row, item) {
      let index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      let ind = this.itemArr[index].tableData.findIndex(v => v.xmId === row.xmId)
      let one = this.itemArr[index].tableData[ind]
      if (e >= 1000000000) {
        this.$message.error('最大输入值不能超过10亿')
        one.rewardValue = null
      }
      // 1 奖 判断上限， 2 惩 判断下限
      if (row.rewardType === 1) {
        if (item.rewardUpLimit && e > item.rewardUpLimit) {
          // 上限不为0 且输入值大于上限值
          this.$message.error('为奖时，输入值不能大于上限值')
          one.rewardValue = null
        }
      } else {
        if (item.rewardLowLimit && Math.abs(e) > Math.abs(item.rewardLowLimit)) {
          // 且下限不为 0 且输入值绝对值大于下限值绝对值
          this.$message.error('为惩时，输入值不能小于下限值')
          one.rewardValue = null
        }
      }
    },
    // 预览图片
    handlePreview(file, row, item) {
      let index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      let ind = this.itemArr[index].tableData.findIndex(v => v.xmId === row.xmId)
      let one = this.itemArr[index].tableData[ind]
      let arr = []
      one.fileList.map(v => {
        arr.push(v.savePath)
      })
      this.$refs.previewModal.show(arr)
      // console.log('tableData', this.itemArr[index].tableData, ind, one)
    },
    // 选择个人或单位事件处理
    handleDeptSelect(value, row, item) {
      console.log('value', value, row, item)
      let index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      console.log('tableData', this.itemArr[index].tableData)

      let ind = this.itemArr[index].tableData.findIndex(v => v.xmId === row.xmId)
      let one = this.itemArr[index].tableData[ind]
      console.log('============', index, ind, one)

      if (one.targetMode === 1) {
        one.targetDeptId = value.id
      } else {
        one.targetUserId = value.id
      }
    },
    // 追加表格列事件处理
    handleTableAdd(item) {
      const index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      let one = this.itemArr[index]
      console.log('one', one)

      one.tableData.push({ xmId: one.tableData.length + 1, targetMode: 1, ...one, tableData: null })
      console.log('tableData', one.tableData)
    },
    // 删除列
    handleDelete(row, item) {
      const index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      const ind = this.itemArr[index].tableData.findIndex(v => v.xmId === row.xmId)
      this.itemArr[index].tableData.splice(ind, 1)
    },
    // 删除项目
    handleDeleteItem(item) {
      let _this = this
      this.$confirm({
        title: '删除操作',
        content: `您确定删除这条记录吗？`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        centered: true,
        async onOk() {
          const index = _this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
          _this.itemArr.splice(index, 1)
        }
      })
    },
    // 删除图片事件处理
    handleRemove(file, fileList, row, item) {
      console.log(file, fileList)
      let index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      console.log('tableData', this.itemArr[index].tableData)

      let ind = this.itemArr[index].tableData.findIndex(v => v.xmId === row.xmId)
      let one = this.itemArr[index].tableData[ind]
      one.fileList = [...fileList]
    },
    // modal 传递过来的数组
    handlePostArr(arr) {
      console.log('arr', arr)
      if (arr.length > 0) {
        arr.map((v, index) => {
          v.tableData = [{ xmId: 1, ...v, targetMode: 1 }]
        })
        this.itemArr = [...arr]
      }
    },
    handleAddItems() {
      this.$refs.declareModal.edit(1, this.itemArr)
    },
    // 提交事件处理
    async handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          let arr = []
          let submit = this.itemArr.every(v => v.tableData.length > 0)
          if (submit) {
            this.itemArr.map(v => {
              v.tableData.map(j => {
                arr.push(j)
              })
            })
            let eventTime = arr.every(v => v.eventDate)
            if (eventTime) {
              this.$set(this.form, 'evalApplyList', arr)
              console.log('arr', arr, this.form)
              const res = await applyCreate(this.form)
              if (res.state === '000000') {
                openNotification('success', '项目申报成功')
                this.$nextTick(() => {
                  // 成功之后清空数据
                  this.itemArr = []
                  this.form.applyTitle = null
                  this.$refs.declareTable.refresh()
                })
              }
            } else {
              this.$message.error('事件时间不能为空')
            }
          } else {
            this.$message.error('每个考评事项至少需要一个考评对象')
          }
        }
      })
    },
    // 上传图片事件处理
    customRequest(info, row, item) {
      // const _this = this
      console.log('customRequest', info)
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      let index = this.itemArr.findIndex(v => v.evalItemId === item.evalItemId)
      console.log('tableData', this.itemArr[index].tableData)

      let ind = this.itemArr[index].tableData.findIndex(v => v.xmId === row.xmId)
      let one = this.itemArr[index].tableData[ind]
      one.fileList = []
      console.log('customRequest', ind, one, one.fileList.length)

      saveOnlyUploads(formData).then(res => {
        if (res.data !== null) {
          const { data } = res
          one.fileList.push(data)
          // this.fileList[this.fileList.length - 1].status = 'done'
          one.fileList[one.fileList.length - 1].url = data.fileUrl + data.fileName
          one.fileList[one.fileList.length - 1].savePath = data.fileUrl + data.fileName
          one.fileList[one.fileList.length - 1].name = data.uploadTitle

          console.log('fileList', one)
          let arr = []
          one.fileList.map(v => {
            arr.push(v.uploadId)
          })
          one.photoList = arr.join(',')

          // this.fileList.map(v => {
          //   v.status = 'done'
          //   v.uploadId = data.uploadId
          //   v.url = data.fileUrl + data.fileName
          // })
          // this.fileList = [...this.fileList]
        }
      })
    }
  },
  created() {
    this.$set(this.form, 'applyUser', this.userInfo.name)
    this.$set(this.form, 'applyUserId', this.userInfo.userId)
    this.$set(this.form, 'applyType', 1)
    this.$set(this.form, 'deptName', this.userInfo.deptName)
    this.$set(this.form, 'applyTime1', this.formatTime(new Date(), 'seconds'))
  }
}
</script>

<style scoped>
.data-table >>> .el-table,
.data-table >>> .el-table .cell,
.data-table >>> .el-table__body-wrapper {
  overflow: inherit;
}
</style>
